package com.questionnaires.repository;

import com.questionnaires.exception.NotExistsException;
import com.questionnaires.model.Question;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ioana.ruca@gmail.com
 */
@Repository
public class QuestionRepositoryImpl implements QuestionRepository{

    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    @Override
    public void saveOrUpdate(Question question) {

        sessionFactory.getCurrentSession().saveOrUpdate(question);
    }

    @Transactional
    @Override
    public void delete(long id) throws NotExistsException {

        Question question = findById(id);
        if (question == null) {
            throw new NotExistsException("No question with id " + id + " exists");
        }
        sessionFactory.getCurrentSession().delete(question);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    @SuppressWarnings("unchecked")
    public List<Question> findAllByQuestionnaire(long questionnaireId) {

        Query query = sessionFactory.getCurrentSession().createQuery(
                "from Question question where question.questionnaire.id=:questionnaireId");
        query.setLong("questionnaireId", questionnaireId);
        return query.list();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Question findById(long id) {

        return (Question) sessionFactory.getCurrentSession().get(Question.class, id);
    }


}
